package cn.rtplay.esp32camcar;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import cn.rtplay.esp32camcar.databinding.FragmentGearAutoBinding;
import cn.rtplay.esp32camcar.toolUtils.LogUtil;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class GearAutoFragment extends Fragment {

    private FragmentGearAutoBinding mViewBinding;
    private final String TAG = "GearAutoFragment";
    private ESP32UDPService mESP32UDPService;
    private boolean mIsStop = false;
    private static final int GEAR_STATE_FORWARD = 0;
    private static final int GEAR_STATE_NEUTRAL = 1;
    private static final int GEAR_STATE_REVERSE = 2;
    private static final int GEAR_STATE_PARKING = 3;
    private int mGearState = GEAR_STATE_PARKING;

    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            LogUtil.v(TAG, "onServiceConnected in");
            mESP32UDPService = ((ESP32UDPService.LocalBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mESP32UDPService = null;
        }
    };

    public GearAutoFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mViewBinding = FragmentGearAutoBinding.inflate(inflater, container, false);
        mViewBinding.gearBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                LogUtil.d(TAG, "onProgressChanged:" + progress);
                mGearState = progress;
                mESP32UDPService.setCarLight(CarLedStatus.LIGHT_REVERSE, mGearState == GEAR_STATE_REVERSE);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        mViewBinding.speedBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                LogUtil.d(TAG, "onProgressChanged:" + progress);
                if ((!mIsStop) && (mESP32UDPService.getChargingState() == ESP32UDPService.CHARGING_STATUS_NOT_CHARGING)) {
                    if (mGearState == GEAR_STATE_REVERSE) {
                        mESP32UDPService.setDriverSpeed(progress, ESP32UDPService.DRIVE_BACKWARDS);
                    } else if (mGearState == GEAR_STATE_FORWARD) {
                        mESP32UDPService.setDriverSpeed(progress, ESP32UDPService.DRIVE_FORWARD);
                    } else {
                        mESP32UDPService.setDriverSpeed(0, ESP32UDPService.DRIVE_FORWARD);
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        mViewBinding.stopButton.setOnTouchListener((view, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: //手指按下
                    mIsStop = true;
                    mESP32UDPService.setDriverSpeed(0, ESP32UDPService.DRIVE_FORWARD);
                    mViewBinding.stopButton.setBackgroundResource(R.drawable.stop_down);
                    mESP32UDPService.setCarLight(CarLedStatus.LIGHT_STOP, true);
                    break;
                case MotionEvent.ACTION_MOVE: //手指移动（从手指按下到抬起 move多次执行）
                    break;
                case MotionEvent.ACTION_UP: //手指抬起
                    mIsStop = false;
                    mViewBinding.stopButton.setBackgroundResource(R.drawable.stop);
                    mESP32UDPService.setCarLight(CarLedStatus.LIGHT_STOP, false);
                    break;
            }
            view.performClick();
            return false;
        });

        Intent esp32ServiceIntent = new Intent(getActivity(), ESP32UDPService.class);
        if (getActivity() != null) {
            getActivity().bindService(esp32ServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
        }
        return mViewBinding.getRoot();
    }
}